<?php
/**
 * Created by Alfred.
 * Date: 2021/8/6
 * Email: silentwolf_wp@163.com
 */
function test_case($out,$obj){
    $arr = [];
    $preg = '/(?<={{).*?(?=}})+/';
    preg_match_all($preg,$out,$arr);
    //json对象转数组
    $obj = json_decode(json_encode($obj),true);
    try{
        $preg0 = '/{{'.$arr[0][0].'}}/';
        $preg1 = '/{{'.$arr[0][1].'}}/';
        //替换数据
        $out = preg_replace($preg0,$obj[trim($arr[0][0])],$out);
        $out = preg_replace($preg1,$obj[trim($arr[0][1])],$out);
        echo $out."<br/>";
    }catch (Exception $e){
        echo $e->getMessage()."<br/>";
    }
}
//test case1
$content = "My name is {{ name }} and I am forever {{ age }}.";
$values = json_decode('{ "name": "Bill", "age": 21 }');
test_case($content,$values);
//test case2
$content = "Say hello to {{ name }}. He is {{ age }}.";
$values = json_decode('{ "name": "Bill", "age": 21, "male": true}');
test_case($content,$values);
//test case3
$content = "Tommy is a good friend of {{ name }}. He lives in {{ city }}.";
$values = json_decode('{ "name": "Bill" } ');
test_case($content,$values);